﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Threading.Tasks;

namespace MDCAdminTool.Commands
{
    public class GetObjectsInRegion : AddTabCommandBindingBase
    {
        public GetObjectsInRegion() : base()
        {
            Command = Application.Current.Resources["GetObjectsInRegionCommand"] as ICommand;
        }

        protected override void OnExecuted( object sender , ExecutedRoutedEventArgs e )
        {
            var cr = e.Parameter as CacheRegion;
            
            if( cr == null ) return;

            var cache = cr.Parent as MdcCache;

            if( cache == null ) return;

            try
            {
                var client    = CacheClientFactory.GetCache( cache );
                var result    = client.GetObjectsInRegion(cr.Name);
                var datacache = CacheClientFactory.GetCache(cache);

                cr.CacheItems.Clear();

                Parallel.ForEach(result, 
                    (x) =>
                     {
                         if (cr.Name.Contains("Default_Region"))
                         {
                             cr.CacheItems.Add( datacache.GetCacheItem( x.Key ) );
                         }
                         else
                         {
                             var item = datacache.GetCacheItem( x.Key , cr.Name );
                             cr.CacheItems.Add(item);
                         }
                         
                     });

                AddNewTab( cr.Name , cr );
            }
            catch (Exception ex)
            {
                cache.Output.Add( ex.Message );
            }
            
        }
    }
}
